package com.jetgege.bluetoothdemo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener,View.OnClickListener {

    BluetoothAdapter mBluetoothAdapter;
    List<BluetoothDevice> devices =new ArrayList<>();
    ListView lv_BluetoothDev;
    BlueListAdapter blueListAdapter;
    OutputStream outputStream;
    InputStream inputStream;
    Button bt_Open;
    Button bt_Close;
    Button bt_SatrtScan;
    Button bt_StopScan;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        lv_BluetoothDev=(ListView)findViewById(R.id.lv_BluetoothDev);
        lv_BluetoothDev.setOnItemClickListener(this);
        blueListAdapter=new BlueListAdapter(devices);
        lv_BluetoothDev.setAdapter(blueListAdapter);


        bt_Open=(Button)findViewById(R.id.bt_Open);
        bt_Close=(Button)findViewById(R.id.bt_Close);
        bt_SatrtScan=(Button)findViewById(R.id.bt_SatrtScan);
        bt_StopScan=(Button)findViewById(R.id.bt_StopScan);

        bt_Open.setOnClickListener(this);
        bt_Close.setOnClickListener(this);
        bt_SatrtScan.setOnClickListener(this);
        bt_StopScan.setOnClickListener(this);
        // Register the BroadcastReceiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_Open:
                if (mBluetoothAdapter == null) {
                    Toast.makeText(this, "设备不支持蓝牙功能", Toast.LENGTH_LONG).show();
                    return;//设备不支持蓝牙功能
                }
                if (!mBluetoothAdapter.isEnabled()) mBluetoothAdapter.enable();
                break;
            case R.id.bt_Close:
                if (mBluetoothAdapter.isEnabled()) mBluetoothAdapter.disable();
                break;
            case R.id.bt_SatrtScan:
                devices.clear();
                mBluetoothAdapter.startDiscovery();
                break;
            case R.id.bt_StopScan:
                mBluetoothAdapter.cancelDiscovery();
                break;
        }
    }


    // Create a BroadcastReceiver for ACTION_FOUND
    BroadcastReceiver mReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add the name and address to an array adapter to show in a ListView
                devices.add(device);
                Log.e("deviceName+++",device.getName());
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))
            {
                if (devices.size()>0) devices.clear();
                Toast.makeText(MainActivity.this, "开始扫描...", Toast.LENGTH_SHORT).show();
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
                Toast.makeText(MainActivity.this, "完成扫描...", Toast.LENGTH_SHORT).show();
                blueListAdapter.notifyDataSetChanged();
            }

        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        conn(devices.get(position));
    }

    BluetoothSocket bluetoothSocket;
    private void conn(final BluetoothDevice device)
    {
        //连接操作为耗时操作，需要开线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取BluetoothSocket，UUID需要和蓝牙服务端保持一致
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));

                    //蓝牙和服务端建立连接
                    bluetoothSocket.connect();
                    //获取输出流，往蓝牙服务端写协议数据
                    outputStream = bluetoothSocket.getOutputStream();
                    inputStream = bluetoothSocket.getInputStream();
                    if (outputStream!=null)
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "连接成功...", Toast.LENGTH_SHORT).show();
                            }
                        });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //写输入数据
    private void writeData(byte [] bytes)
    {
        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void readData() {
        byte[] buffer;  // buffer store for the stream
        try {
            buffer = new byte[inputStream.available()];
        // Keep listening to the InputStream until an exception occurs
            int  bytes = inputStream.read(buffer);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void cancel() {
        try {
            bluetoothSocket.close();
        } catch (IOException e) { }
    }


}
